<?php
/*****************
*版权所有：刘景峰
*联系方式：13810908686
*电子邮件：ljf1279@yeah.net
******************/
include("../inc/head.php");
include("../inc/fckeditor.php");

$D_ID = (int) $_REQUEST['D_ID'];
$CreateTime = time();
$Doc = new Object();
{DOC_CONF}
if ($_POST['doPost'] == "true") {
	
	//队列处理，删除处理
	if ( !empty($D_ID)) {
		
		$old_url  = trim($_POST['old_url']);
		$new_url  = trim($_POST['url']);
		
		if ($old_url != $new_url) {
			
			$site_id = (int) $_POST['site_id'];
			$file_row = checkIsTask($site_id, 0);

			if ( !empty($file_row) ) {
				//把删除url放入到具体的删除文件中
				$row1 = urlToWebUrl($old_url);
				$row2 = urlToWebUrl($new_url);
				editDocCollectUrl($file_row['mDeleteFile'], $file_row['mEditFile'], DOC_ROOT.$old_url, DOC_ROOT.$new_url );
				editDocCollectUrl($file_row['mCdnDeleteFile'], $file_row['mCdnEditFile'], $row1['web_url'], $row2['web_url']);
				unset($row1, $row2);
				
				if ( is_file(DOC_ROOT.$old_url) ) {
				    unlink(DOC_ROOT.$old_url);
				}
			}
		}
		//删除队列
		queueDelete(0, $D_ID);
	}
	
	foreach ($_POST as $key => $val) {
		
		if ( is_array($val) ) {
			$val = implode(",",$val);
		}
		$post[$key] = $val;
	}
	
	$Doc = new Object($post);
	if ( !$Doc->url ) {
		$Doc->url = $Template->UrlRule;
	}
	
	$Doc->CreateTime = 0;

	$is_new = is_numeric($D_ID) ? false : true;
	///////////////////////////////////////////////////////////
	
	if ( eregi("\[paganation\].*\n\[[^\]]+\]", $Template->Config) ) {
		
		$page_conf = eregi_replace("^.*\[paganation\](.*)\n\[[^\]]+\].*$","\\1",$Template->Config);
	} elseif ( eregi("\[paganation\].*$", $Template->Config) ) {
		$page_conf = eregi_replace("^.*\[paganation\](.*)$","\\1",$Template->Config);
	}
	
	if ( $page_conf ) {
		
		foreach ($Doc as $k => $v) {
			$Doc_arr[$k] = $v;	
		}
		$page_conf = ereg_replace("^[\n\r ]+","",$page_conf);
		$page_conf = ereg_replace("[\n\r; ]$","",$page_conf);
		$lines = split(";",$page_conf);
		unset($page_conf);
		$page_conf = array();
		
		for ( $i=0; $i < count($lines); $i++) {
			
			list($k,$v) = split("=>",$lines[$i]);
			$k = trim($k);
			$v = trim($v);
			$page_conf[strtolower($k)] = $v;
		}
		
		if ($page_conf['contentfield'] && $page_conf['titlefield']) {
			
			if (eregi("<div[^>]*page\-break\-after\:[^>]*>[^>]*<span[^>]*>[^<]*<[^a-z]+span>[^>]*<[^a-z]+div>",$Doc->{$page_conf['contentfield']})) {
				
				$page_title[0] = $Doc->{$page_conf['titlefield']};
				preg_match_all("/<div[^>]*page\-break\-after\:[^>]*>[^>]*<span[^>]*>([^<]*)<[^a-z ]+span>[^>]*<[^a-z ]+div>/sU",$Doc->{$page_conf['contentfield']},$o,PREG_PATTERN_ORDER);
				for ($i=0; $i< count($o[1]); $i++) {
					$page_title[$i+1] = ereg_replace("^(\&nbsp;)+","",trim($o[1][$i]));
					if( !$page_title[$i+1] ) {
						$page_title[$i+1] = $page_title[0]."(".($i+2).")";
					}
				}
			
				$page_content = spliti("<div[^>]*page\-break\-after\:[^>]*>[^>]*<span[^>]*>[^<]*<[^a-z]+span>[^>]*<[^a-z]+div>",$Doc->{$page_conf['contentfield']});
				for ($i=0; $i<count($page_content); $i++) {
				
					$Docs[$i] = new Object($Doc_arr);
					$Docs[$i]->{$page_conf['contentfield']} = $page_content[$i];
					$Docs[$i]->{$page_conf['titlefield']} = $page_title[$i];
					if ( $i>0 ) {
						$Docs[$i]->url = $Template->UrlRule;//createDoc($Docs[$i]);
					}
				}
			}
		}
	}

	if ($Docs) {
		$DocCount = count($Docs);
		for( $i = 0; $i<$DocCount; $i++) {
			$Docs[$i]->page_num = $i + 1;
			if($i>0 || $is_new)
			{
				add($Docs[$i]);
			}
			$Docs[$i]->url = createDoc($Docs[$i]);
			$req = 1;//update($Docs[$i]);
		}
		$page_conf['page_first'] = $Docs[0]->url;
		$page_conf['page_last'] = $Docs[$i-1]->url;
		if($page_conf['urlsrc'])
		{
			$page_conf['page_first'] = str_replace($page_conf['urlsrc'],$page_conf['urlreplace'],$page_conf['page_first']);
			$page_conf['page_last'] = str_replace($page_conf['urlsrc'],$page_conf['urlreplace'],$page_conf['page_last']);
		}

		$page_show = $page_conf['page_show'];
	
		foreach ($Docs as $k=>$v)
		{
			$page_priv = $k>0?$Docs[$k-1]->url:$Docs[0]->url;
			$page_next = $k<$DocCount-1?$Docs[$k+1]->url:$Docs[$DocCount-1]->url;
			if($k == $DocCount-1)
			{
				$page_next = $Docs[0]->url;
			}
			if($k == 0)
			{
				$page_priv = $Docs[$DocCount - 1]->url;
			}
			if($page_conf['urlsrc'])
			{
				$page_priv = str_replace($page_conf['urlsrc'],$page_conf['urlreplace'],$page_priv);
				$page_next = str_replace($page_conf['urlsrc'],$page_conf['urlreplace'],$page_next);
			}
		
			$loop = '';//;
			$list_loop = '';

			$page_start = 0;
			$page_end = $DocCount;
			
			if($page_show > 2 && $page_show < $DocCount)
			{
				$page_start = $k - floor($page_show / 2);
				if($page_start < 0)
				{
					$page_start = 0;
				}
				$page_end = $page_start + $page_show;
				if($page_end > $DocCount)
				{
					$page_end = $DocCount;
					$page_start = $page_end - $page_show;
					if($page_start < 0)
					{
						$page_start = 0;
					}
				}
			}

			for($i=0;$i<$DocCount;$i++)
			{
				$page_url = $page_conf['urlsrc']?str_replace($page_conf['urlsrc'],$page_conf['urlreplace'],$Docs[$i]->url):$Docs[$i]->url;
				$page_title = htmlspecialchars($Docs[$i]->{$page_conf['titlefield']});
				if(isset($page_conf['page_list']))
				{
					if($i == $k && isset($page_conf['list_curr']))
					{
						$list_loop .= str_replace('{page_num}',($i+1),str_replace('{page_url}',$page_url,str_replace('{page_title}',$page_title,$page_conf['list_curr'])));
					}
					elseif(isset($page_conf['list_option']))
					{
						$list_loop .= str_replace('{page_num}',($i+1),str_replace('{page_url}',$page_url,str_replace('{page_title}',$page_title,$page_conf['list_option'])));
					}
				}
				else
				{
					$page_conf['page_list'] = '';
				}
				if($i>=$page_start && $i<$page_end)
				{
					if($i==$k && isset($page_conf['curpage']))
					{
						$loop .= str_replace('{page_num}',$i+1,str_replace('{page_url}',$page_url,$page_conf['curpage']));
					}
					else 
					{
						$loop .= str_replace('{page_num}',$i+1,str_replace('{page_url}',$page_url,$page_conf['loop']));
					}
				}
			}
			if(isset($page_conf['page_dot']))
			{
				if($page_start > 0)
				{
					$loop = str_replace('{page_num}',1,str_replace('{page_url}',$page_conf['page_first'],$page_conf['loop'])) . $page_conf['page_dot'] . $loop; 
				}
				if($page_end < $DocCount)
				{
					$loop .= $page_conf['page_dot'] . str_replace('{page_num}',$DocCount,str_replace('{page_url}',$page_conf['page_last'],$page_conf['loop'])); 
				}
			}
			$paganation = $page_conf['style']; 
			$paganation = str_replace('{page_first}',$page_conf['page_first'],$paganation);
			$paganation = str_replace('{page_last}',$page_conf['page_last'],$paganation);
			$paganation = str_replace('{page_priv}',$page_priv,$paganation);
			$paganation = str_replace('{page_next}',$page_next,$paganation);
			$paganation = str_replace('{loop}',$loop,$paganation);

			$page_list = isset($page_conf['page_list'])?$page_conf['page_list']:'';
			$page_list = str_replace('{list_loop}',$list_loop,$page_list);

			$Docs[$k]->{$page_conf['contentfield']} = ereg_replace("(<img[^>]*>)","<a href=\"".$page_next."\">\\1</a>",$Docs[$k]->{$page_conf['contentfield']});
			
			$Docs[$k]->{$page_conf['contentfield']} = $page_list . $Docs[$k]->{$page_conf['contentfield']} . $paganation;
			update($Docs[$k]);
			if(!eregi("^https?:",$Docs[$k]->url))
			{
				echo createDoc($Docs[$k]);
			}
		}
	}
	else 
	{
		$Doc->page_num = 1;
		if ( empty($D_ID) ) {
			$req = add($Doc);
		} else  {
			$req = update($Doc);
		}

	}
	
	if($TID == 2)
	{
		$CommentCode = 'pop-' . $Doc->TID . '-' . $Doc->D_ID;
		$CommentTitle = urlencode($Doc->{标题});
		$CommentUrl = urlencode($Doc->url);
		$CommentChannel = 'pop';
		echo '<script src="http://www.zoshow.com/comment.php?status=Y&act=newComment&u=fdsajkjklfdsajkfoiweuq&title='.$CommentTitle.'&comment_code='.$CommentCode.'&channel='.$CommentChannel.'&url='.$CommentUrl.'"></script>';
	}
	
	if($req)
	{
		$q = $_SERVER['QUERY_STRING'];
		$suffix_url = '';
		if(!empty($q))
		{
			$suffix_url.='?'.$q;
		}
		new ActionLog(array("LogType"=>"doc_{$TID}_sucess","Action"=>"{$req},$D_ID\t{$currAdmin->AID}"));
		
		( empty($D_ID) ) ? alert("增加成功，请发布。","location","docList_$TID.php{$suffix_url}")
						 : alert("修改成功，请发布。","location","docList_$TID.php{$suffix_url}");//2010.05.05预览功能修改

	}
	else
		new ActionLog(array("LogType"=>"doc_{$TID}_err","Action"=>"{$req},$D_ID\t{$currAdmin->AID}"));
		alert("err","location",$_SERVER["SCRIPT_NAME"]);
	exit;
} else {
	
	if ( !empty($D_ID) ) {
		
		$Doc->getObjById($D_ID, "D_ID", $DTName);
		$CreateTime = $Doc->CreateTime;
		//加入队列处理
		queueInfo($D_ID);
	}
	
}

if(!$Doc->url)
	$Doc->url = $Template->UrlRule;
$Doc->TID = $TID;


function update($Doc)
{
	global $db;
	$sql = "{SQL_UPDATE}";

	if($db->query($sql))
	{
		return true;
	}
	return false;
}
function add(&$Doc)
{
	global $db;
	$sql = "{SQL_INSERT}";
	$sql .= ', MendTime = '.time();
	
	if($db->query($sql))
	{
		$Doc->D_ID = $db->insert_id();		 
		return true;
	}
	return false;
}

function createDoc(&$Doc)
{
	if(!eregi('^http://',$Doc->url) && eregi("\.exe$",$Doc->url))
	{
		$Doc->url .= '.html';
	}
	$path = $Doc->url;
	if(!eregi("^http:\/\/",$path))
	{
		global $Template,$db;
		//
		{DOC_CREATE}
//		
		$Doc->YYYY = date("Y",$Doc->CreateTime);
		$Doc->MM = date("m",$Doc->CreateTime);
		$Doc->DD = date("d",$Doc->CreateTime);
		$Doc->HH = date("H",$Doc->CreateTime);
		$Doc->II = date("i",$Doc->CreateTime);
		$Doc->SS = date("s",$Doc->CreateTime);
		$file = $Template->Style;

		//处理全局变量
		preg_match_all ("/\\\$G\{([^\s\}]+)\}/", $file, $matches);
		for ($i=0; $i< count($matches[0]); $i++) 
		{
			$Global = new Object();
			$Global->getObjById($matches[1][$i],'Title','Global');
			if($Global->GID > 0)
			{
				$file = str_replace($matches[0][$i], $Global->Content, $file);
			}
		}
		//处理内容
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $file, $matches);
		for ($i=0; $i< count($matches[0]); $i++) 
		{
			if(isset($Doc->$matches[1][$i]))
				$file = str_replace($matches[0][$i], $Doc->$matches[1][$i], $file);
		}
		$file = stripslashes($file);
		//二次处理
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $file, $matches);
		for ($i=0; $i< count($matches[0]); $i++) 
		{
			if(isset($Doc->$matches[1][$i]))
				$file = str_replace($matches[0][$i], $Doc->$matches[1][$i], $file);
		}
		
		//处理URL
		preg_match_all ("/\\$\{([^\s\}]+)\}/", $path, $matches);
		for ($i=0; $i< count($matches[0]); $i++) 
		{
			if(isset($Doc->$matches[1][$i]))
				$path = str_replace($matches[0][$i], $Doc->$matches[1][$i], $path);
		}
		/******2010.05.05预览功能修改***************/
		//$version_url="/tmp";
		//判断是否为根层
		if ($Template->PID==0){
			//$path_tmp = $version_url."/".$path;
		}else{
			
			//$path_tmp = "/".$path;
			//加入创建时间信息
			$file = $file."
			<!--{$Doc->TID}_{$Doc->D_ID}_".date("Y-m-d H:i:s")."-->";
			//创建/更新文件
			$cache = new Cache(array("Content"=>$file,"FilePathName"=>DOC_ROOT.$path));
			$cache->update(true);
		}
       
		/**********end****************/
		
		return $path;
	}
}
?>
<script language="javascript" type="text/javascript">
<?php echo $Template->Script; ?>

</script>
<script type="text/javascript" src="/wondershare/js/jquery.suggest.js"></script>
<script type="text/javascript" src="/wondershare/js/task.js"></script>
<link rel="stylesheet" type="text/css" href="/wondershare/styles/jquery.suggest.css" />
<script>

function is_exist_file(tem_id, tem_tables, tem_url)
{
		var old_url = $("#old_url").val();
       var result = false;
        $.ajax({
        async:false ,//要设置为同步的，要不CheckInputUrl的返回值永远为false
		type: "GET"
        ,url:'/wondershare/syn_template.php?action=is_exist_file'
        ,data:{tem_id: tem_id,tem_tables:tem_tables,tem_url:tem_url,old_url:old_url}
        ,success:function(data)
		{
    	
                if(data == 1)
		         {
                    result = false;
                } else {
                   result = true;
                }
        }});
        return result;
}

</script>

<!--自动生成form start-->
<?php 
if($Doc->TID == 134)
{
?>
<input type="hidden" name="p_id" id="p_id"  value=""/>
<?php }?>
{VAR_FORM}
<!--自动生成form end-->

<?php
include("../inc/foot.php");
?>
